package com.ragdollcat.thirdaicodegenerate.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring获取Bean的工具类
 */
@Component
public class SpringBeanUtil implements ApplicationContextAware {

    /**
     * Spring应用上下文环境
     */
    private static ApplicationContext applicationContext;

    /**
     * 实现ApplicationContextAware接口的回调方法，设置上下文环境
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtil.applicationContext = applicationContext;
    }

    /**
     * 获取ApplicationContext
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    /**
     * 根据Bean的名称获取Bean实例
     * @param name Bean的名称
     * @return Bean实例
     */
    public static Object getBean(String name) {
        checkApplicationContext();
        return applicationContext.getBean(name);
    }

    /**
     * 根据Bean的类型获取Bean实例
     * @param clazz Bean的类型
     * @param <T> 泛型
     * @return Bean实例
     */
    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return applicationContext.getBean(clazz);
    }

    /**
     * 根据Bean的名称和类型获取Bean实例
     * @param name Bean的名称
     * @param clazz Bean的类型
     * @param <T> 泛型
     * @return Bean实例
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        checkApplicationContext();
        return applicationContext.getBean(name, clazz);
    }

    /**
     * 检查ApplicationContext是否为null
     */
    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("Spring上下文未初始化，请检查是否已正确配置Spring");
        }
    }
}
